﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace lchealthy
{
    public partial class frmCustomerBuy : Form
    {
        int pid = 1;//产品的ID号
        DataSet ds, dsBuy;
        int userid = 0;
        int flg;
        //public frmCustomerBuy()
        // {
        //     InitializeComponent();
        // }
        public frmCustomerBuy(int id, int flag)
        {
            userid = id;
            flg = flag;//判断购买还是寄存
            InitializeComponent();
        }
        //刷新页面
        private void proBind()
        {

            string sql = "SELECT ProductInfo.PID, PName, PPrice, PUsing, PExplain ,Inum FROM ProductInfo LEFT JOIN inventory ON ProductInfo.PID = inventory.Pid where inventory.did= "+userinfo.id;
            ds = DbHelperOleDb.Query(sql);
            dgvPro.AutoGenerateColumns = false;

            dgvPro.DataSource = ds.Tables[0];
            //单元格内内容比较多时，设置自动换行
            dgvPro.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            //设置根据内容的多少自动调整单元格的高度
            dgvPro.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;

        }

        private void frmCustomerBuy_Load(object sender, EventArgs e)
        {
            if (flg == 2)
            {
                btnBuy.Visible = false;
            }
           // lblPro.Text = this.Text + "是：\r\n";
            if (flg == 2)
            {
                lblPro.Text = "寄存产品是：\r\n";
                label1.Text = "寄存数量";
            }
            if (flg == 1)
            {
                lblPro.Text = "购买产品是：\r\n";
                label1.Text = "购买数量";
            }
            proBind();
            createTable();
        }
        //单击产品列表表格时
        private void dgvPro_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = -1;
            row = dgvPro.CurrentRow.Index;
            //得到选中产品的ID
            pid = int.Parse(ds.Tables[0].Rows[row]["PID"].ToString());
            string proName = ds.Tables[0].Rows[row]["PName"].ToString();
            lblProName.Text =proName;            
            txtNum.Focus();
            txtNum.Text = "";
        }
        //创建购物车的表   
        public void createTable()
        {
            dsBuy = new DataSet();

            using (DataTable dt = new DataTable("buy"))
            {    //创建列            
                DataColumn dtc = new DataColumn("产品ID", typeof(string));
                dt.Columns.Add(dtc);
                dtc = new DataColumn("产品名称", typeof(string));
                dt.Columns.Add(dtc);
                dtc = new DataColumn("产品数量", typeof(int));
                dt.Columns.Add(dtc);


                dtc = new DataColumn("产品价格", typeof(double));
                dt.Columns.Add(dtc);
                dtc = new DataColumn("产品总价", typeof(double));
                dt.Columns.Add(dtc);
                //添加数据到DataTable      
                DataRow dr = dt.NewRow();
                dr["产品名称"] = "总价：";
                dr["产品数量"] = 0;
                //dr["产品总额"] = 23;
                dt.Rows.Add(dr);

                dsBuy.Tables.Add(dt);
            }
        }
        //店中寄存按钮
        private void btnInvent_Click(object sender, EventArgs e)
        {
            //frmCustorInventer f = new frmCustorInventer();
            //f.Show();
            int bpid = 0, num = 0;
            string sql = "";
            for (int i = 0; i < dsBuy.Tables[0].Rows.Count - 1; i++)
            {
                bpid = int.Parse(dsBuy.Tables[0].Rows[i][0].ToString());
                num = int.Parse(dsBuy.Tables[0].Rows[i][2].ToString());
                sql = string.Format("insert into depositinfo(pid,cid,dpnum) values({0},{1},{2})", bpid, userid, num);
                DbHelperOleDb.ExecuteSql(sql);
                string sq = "SELECT pid ,dpnum FROM indepositinfo where Pid=" + bpid + " and cid=" + userid;
                DataSet da = DbHelperOleDb.Query(sq);
                if (da.Tables[0].Rows.Count == 1)
                {
                    //int m = (int)da.Tables[0].Rows[0]["dpnum"];
                    string sql1 = string.Format("update indepositinfo set dpnum =dpnum+{0} where [Pid] = {1}", num, bpid);
                    int k = DbHelperOleDb.ExecuteSql(sql1);
                }
                else
                {
                    string sql1 = string.Format("INSERT INTO indepositinfo (Pid,dpnum,cid ) VALUES ({0},{1},{2})",bpid, num,userid);
                    int k = DbHelperOleDb.ExecuteSql(sql1);
                }
            }



            MessageBox.Show("寄存成功！");
            this.Close();
        }


        //点击确定第二表（购物车）生成数据
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            bool ishave = false;
            for (int i = 0; i < dsBuy.Tables[0].Rows.Count - 1; i++)
            {
                if (pid.ToString() == dsBuy.Tables[0].Rows[i][0].ToString())
                    ishave = true;
            }
            if (!ishave)
            {
                string proName = ds.Tables[0].Rows[dgvPro.CurrentRow.Index]["PName"].ToString();
                double proPrice = double.Parse(ds.Tables[0].Rows[dgvPro.CurrentRow.Index]["PPrice"].ToString());
                int num = int.Parse(txtNum.Text);
                double sum = proPrice * num;
                DataRow dr = dsBuy.Tables[0].NewRow();
                dr[0] = pid;
                dr[1] = proName;
                dr[2] = num;
                dr[3] = proPrice;
                dr[4] = sum;
                dsBuy.Tables[0].Rows.InsertAt(dr, dsBuy.Tables[0].Rows.Count - 1);
                dsBuy.Tables[0].AcceptChanges();

                dgvBuy.DataSource = dsBuy.Tables[0];

                object sumObject = dsBuy.Tables[0].Compute("sum([产品总价])", "");
                dsBuy.Tables[0].Rows[dsBuy.Tables[0].Rows.Count - 1][2] = sumObject.ToString();
                //lblSum.Text = sumObject.ToString() ;
                dgvBuy.Columns[0].ReadOnly = true;
                dgvBuy.Columns[1].ReadOnly = true;
                dgvBuy.Columns[3].ReadOnly = true;
                dgvBuy.Columns[4].ReadOnly = true;
                //dgvBuy.Columns[1].ReadOnly = true;
            }
            else
            {
                MessageBox.Show("已购买过这个产品，可以直接修改数量！");
            }

        }
        //当客户选择的产品数量有变化时候，产品总价格也要变化
        private void dgvBuy_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            getsum();

        }
        //得到产品的总价格
        private void getsum()
        {
            for (int i = 0; i < dsBuy.Tables[0].Rows.Count - 1; i++)
            {
                dsBuy.Tables[0].Rows[i][4] = (float.Parse(dsBuy.Tables[0].Rows[i][3].ToString()) * float.Parse(dsBuy.Tables[0].Rows[i][2].ToString())).ToString();
            }
            object sumObject = dsBuy.Tables[0].Compute("sum([产品总价])", "");
            dsBuy.Tables[0].Rows[dsBuy.Tables[0].Rows.Count - 1][2] = sumObject.ToString();
        }

        private void dgvBuy_BindingContextChanged(object sender, EventArgs e)
        {

        }

        private void dgvBuy_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {


        }

        private void dgvBuy_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (e.Row.Cells[1].Value.ToString() == "总价：")
            {
                e.Cancel = true;
                MessageBox.Show("汇总行不能删除！");
            }
            else
            {
                getsum();
            }

        }

        private void txtNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                btnConfirm_Click(null, null);
            }
        }
        //购买按钮
        private void btnBuy_Click(object sender, EventArgs e)
        {
            int bpid = 0, num = 0;
            string pname;
            string sql = "";
            //当购买产品后产品的数量会发生改变
            for (int i = 0; i < dsBuy.Tables[0].Rows.Count - 1; i++)
            {
                bpid = int.Parse(dsBuy.Tables[0].Rows[i][0].ToString());
                num = int.Parse(dsBuy.Tables[0].Rows[i][2].ToString());
                pname = dsBuy.Tables[0].Rows[i][1].ToString();
                sql = string.Format("insert into recordsinfo(pid,cid,ramount) values({0},{1},{2})", bpid, userid, num);
                DbHelperOleDb.ExecuteSql(sql); ;
                sql = string.Format("update inventory set inum=inum-{0} where pid={1}", num, bpid);
                // DialogResult ys = MessageBox.Show("确认要购买"+pname+num.ToString()+"瓶吗？","确认信息",MessageBoxButtons.YesNo);
                //  if (ys == DialogResult.Yes)

                DbHelperOleDb.ExecuteSql(sql);


            }

            MessageBox.Show("购买成功！");
            //刷新页面，使产品列表的库存有所变化
            btnBuy.Enabled = false;
            proBind();

        }




    }
}
